from flask import flash, redirect, url_for, render_template
from flask_login import login_required, current_user

from app.libs.email import send_mail
from app.models.base import db
from app.models.gifts import Gift
from app.models.wish import Wish
from app.view_model.wish import MyWishes
from . import web


@web.route('/my/wish')
@login_required
def my_wish():
    uid = current_user.id
    # 我的全部礼物
    wishes_of_me = Wish.get_user_wishes(uid)
    wishes_isbn_list = [wish.isbn for wish in wishes_of_me]
    # 我的礼物有几人想要
    gifts_count_list = Wish.get_gifts_counts(wishes_isbn_list)

    wishes_view_model = MyWishes(wishes_of_me, gifts_count_list)
    return render_template('my_wish.html', wishes=wishes_view_model.gifts)


@web.route('/wish/book/<isbn>')
@login_required
def save_to_wish(isbn):
    if current_user.can_save_to_list(isbn):
        with db.auto_commit():
            wish = Wish()
            wish.uid = current_user.id
            wish.isbn = isbn
            db.session.add(wish)
    else:
        flash('不要重复添加')
    return redirect(url_for('web.book_detail', isbn=isbn))


@web.route('/wish/book/<isbn>/redraw')
@login_required
def redraw_from_wish(isbn):
    wish = Wish.query.filter_by(isbn=isbn, launched=False).first_or_404()
    with db.auto_commit():
        wish.delete()
    return redirect(url_for('web.my_wish'))


@web.route('/satisfy/wish/<int:wid>')
def satisfy_wish(wid):
    wish = Wish.query.get_or_404(wid)
    gift = Gift.query.filter_by(uid=current_user.id, isbn=wish.isbn).first()
    if not gift:
        flash('你还没有这个礼物，请加入到赠送清单中')
    else:
        send_mail(wish.user.email, '有人想要赠送你一本书', 'email/satisify_wish.html', wish=wish, gift=gift)
        flash('已经向目标发送一封邮件，他接受后会你会受到一个鱼漂')
    return redirect(url_for('web.book_detail', isbn=wish.isbn))